package cn.lifei.auth.interceptor;

import cn.lifei.auth.service.IEmployeeRoleService;
import cn.lifei.basic.annotation.LifeiPermission;
import cn.lifei.basic.data.ContextMap;
import cn.lifei.org.domain.Employee;
import cn.lifei.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * 这个拦截器类用于 权限拦截
 * 权限： 认证 和 鉴权
 * 注册拦截器在启动类里面
 */
@Component
public class AUthInterceptor implements HandlerInterceptor {
    @Autowired
    private IEmployeeService employeeService;



    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //false：拦截  true：放行
//        System.out.println("+++++++++++++++++开始拦截+++++++++++++++++++");
        /**
         * 进行认证：
         *      获取前端的token
         *      根据token获取map中的对象（有对象说明登录）
         */
        //获取前端的token 从header中获取请求
        String token = request.getHeader("token");
        System.out.println(token);
        if (Objects.isNull(token)){
            //没有登录应该被拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        Employee employee = ContextMap.loginMap.get(token);
        if (Objects.isNull(employee)){
            //没有登录应该被拦截
            response.getWriter().print("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }



        //鉴权
        //1.判断访问的资源 是否需要权限  判断请求的方法 是否有权限注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        LifeiPermission annotation = method.getAnnotation(LifeiPermission.class);
        if (Objects.nonNull(annotation)){
            //2.如果需要权限
            //3.获取用户权限
            //根据用户的id 查询 角色id 再查 角色拥有的权限
            List<String> permissions = employeeService.queryPermissionsById(employee.getId());
            //4.获取资源权限
            String name = method.getName();
            String simpleName = handlerMethod.getBeanType().getSimpleName();
            String resourceUrl = simpleName + ":"+name;
            System.out.println(resourceUrl);
            //5.判断用户权限是否包含资源权限
            boolean contains = permissions.contains(resourceUrl);
            if (!contains){
                response.getWriter().print("{\"success\":false,\"msg\":\"noPermission\"}");

                return false;
            }
        }

        return true;
    }
}
